package com.jeejio.train.service.impl;

import com.jeejio.train.dao.AttachMapper;
import com.jeejio.train.dao.CourseMapper;
import com.jeejio.train.entity.Attach;
import com.jeejio.train.entity.Course;
import com.jeejio.train.entity.Lecturer;
import com.jeejio.train.service.AttachService;
import com.jeejio.train.util.IConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.List;

@Service
@Transactional
public class AttachServiceImpl implements AttachService {
    private static final Logger LOG = LoggerFactory.getLogger(AttachServiceImpl.class);

    @Autowired
    private AttachMapper attachMapper = null;

    @Autowired
    CourseMapper courseMapper = null;

    @Override
    public List<Attach> findAttachByCourse(int courseId) {
        return attachMapper.findByCourseId(courseId);
    }

    @Override
    public boolean upload(Attach attach) {
        if (attachMapper.insert(attach) > 0) {
            return true;
        }
        return false;
    }

    @Override
    public Attach findByPrimaryKey(int id) {
        return attachMapper.selectByPrimaryKey(id);
    }

    @Override
    public int deleteByPrimaryKey(int id, Lecturer lecturer) {
        Attach attach = attachMapper.selectByPrimaryKey(id);
        if (null == attach) {
            return IConstant.E_ATTACH_DELETE_FILE_NOT_FOUND;
        }
        Course course = courseMapper.selectByPrimaryKey(attach.getCourseId());
        if (null == course) {
            return IConstant.E_ATTACH_DELETE_COURSE_NOT_FOUND;
        }
        if (lecturer.getId() != course.getLecturer().getId()) {
            return IConstant.E_ATTACH_DELETE_NO_PERMISSION;
        }
        // 删除文件
        File file = new File(attach.getRelativePath() + File.separatorChar + attach.getFileName());
        if (!file.delete()) {
            return IConstant.E_ATTACH_DELETE_FILE_FAILED;
        }
        // 删除空文件夹
        File dir = new File(attach.getRelativePath());
        if (0 == dir.list().length) {
            if (!dir.delete()) {
                LOG.warn("附件空文件夹删除失败：" + dir.getAbsolutePath());
            }
        }
        // 删除数据库记录
        if (attachMapper.deleteByPrimaryKey(id) > 0) {
            return IConstant.SUCCESS;
        }
        return IConstant.E_ATTACH_DELETE_FAILED;
    }
}
